<?php defined('SYSPATH') or die('No direct script access.');
class Controller_Commission extends Stourweb_Controller
{
    public function action_dialog_commission_set()
    {
        $type_id = Arr::get($_GET,'type_id');
        $settlement_id = Arr::get($_GET,'settlement_id');
        $channel_id = Arr::get($_GET,'channel_id');
        $suit_id = Arr::get($_GET,'suit_id');

        $this->assign('type_id',$type_id);
        $this->assign('channel_id',$channel_id);
        $this->assign('suit_id',$suit_id);
        $this->assign('settlement_id',$settlement_id);
        $this->display('stourtravel/commission/dialog_set_commission');
    }

    public function action_ajax_save_commission()
    {
        $type_id = Arr::get($_POST,'type_id');
        $suit_id = Arr::get($_POST,'suit_id');
        $channel_id = Arr::get($_POST,'channel_id');
        $settlement_id = Arr::get($_POST,'settlement_id');
        $settlement_key = Arr::get($_POST,'settlement_key');
        $settlement_val = Arr::get($_POST,'settlement_val');
        if(!$type_id || !$suit_id || !$channel_id || !$settlement_id || !$settlement_key || !$settlement_val){
            exit(json_encode(array(
                'status' => false,
                'msg'    => '参数缺失'
            )));
        }
        $suit_id = json_decode($suit_id,true);
        if($settlement_id==1){
            self::set_profit($_POST);
        }else{
            /*修改销售价抽佣比例*/
            $data = array(
                'settlement_key' => $settlement_key,
                'settlement_val' => $settlement_key==1?bcdiv($settlement_val,100,2):$settlement_val,
            );
            foreach ($suit_id as $v){
                $is_exist = DB::select()->from('supplier_settlement_config')
                    ->where("type_id={$type_id} and suit_id={$v} and channel_id={$channel_id}")
                    ->execute()->valid();
                if($is_exist){
                    DB::update('supplier_settlement_config')->set($data)->where("type_id={$type_id} and suit_id={$v} and channel_id={$channel_id}")->execute();
                }else{
                    $data['suit_id'] = $v;
                    $data['type_id'] = $type_id;
                    $data['channel_id'] = $channel_id;
                    DB::insert('supplier_settlement_config',array_keys($data))->values(array_values($data))->execute();
                }
            }
        }
        echo json_encode(array(
            'status' => true
        ));
    }

    /**
     * @param $params
     * 设置利润
     */
    public function set_profit($params)
    {
        $suit_id = json_decode($params['suit_id'],true);
        $settlement_key = $params['settlement_key'];
        $settlement_val = $params['settlement_val'];
        $date = strtotime(date('Ymd'));
        if($settlement_key==1){
            /*百分比时 在供应价基础上 上浮作为利润*/
            $settlement_val = bcdiv($settlement_val,100,2);
            foreach ($suit_id as $v){
                switch ($params['type_id'])
                {
                    case 1:
                        $set = array(
                            'adultprofit'    => "adultbasicprice*{$settlement_val}",
                            'adultprice'     => "adultbasicprice+adultprofit",
                            'childprofit'    => "childbasicprice*{$settlement_val}",
                            'childprice'     => "childbasicprice+childprofit",
                            'oldprofit'      => "oldbasicprice*{$settlement_val}",
                            'oldprice'       => "oldbasicprice+oldprofit",
                            'people4_profit' => "people4_basicprice*{$settlement_val}",
                            'people4_price'  => "people4_basicprice+people4_profit",
                            'people5_profit' => "people5_basicprice*{$settlement_val}",
                            'people5_price'  => "people5_basicprice+people5_profit",
                            'people6_profit' => "people6_basicprice*{$settlement_val}",
                            'people6_price'  => "people6_basicprice+people6_profit",
                        );
                        $sql_arr = array();
                        foreach ($set as $k=>$s){
                            array_push($sql_arr,$k.'='.$s);
                        }
                        $sql_arr = implode(',',$sql_arr);
                        $sql = "UPDATE sline_line_suit_price SET {$sql_arr} ";
                        $sql.= "WHERE suitid={$v} AND day>={$date} AND supplier_channel_id={$params['channel_id']}";
                        DB::query(1, $sql)->execute();
                        break;
                    case 2:
                        $sql = "UPDATE sline_hotel_room_price SET profit=basicprice*{$settlement_val},price=basicprice+profit ";
                        $sql.= "WHERE suitid={$v} AND day>={$date} AND supplier_channel_id={$params['channel_id']}";
                        DB::query(1, $sql)->execute();
                        break;
                    case 3:
                        $sql = "UPDATE sline_car_suit_price SET adultprofit=adultbasicprice*{$settlement_val},adultprice=adultbasicprice+adultprofit ";
                        $sql.= "WHERE suitid={$v} AND day>={$date} AND supplier_channel_id={$params['channel_id']}";
                        DB::query(1, $sql)->execute();
                        break;
                    case 5:
                        $sql = "UPDATE sline_spot_ticket_price SET adultprofit=adultbasicprice*{$settlement_val},adultprice=adultbasicprice+adultprofit ";
                        $sql.= "WHERE ticketid={$v} AND day>={$date} AND supplier_channel_id={$params['channel_id']}";
                        DB::query(1, $sql)->execute();
                        break;
                    case 13:
                        $sql = "UPDATE sline_tuan SET profit=basicprice*{$settlement_val},price=basicprice+profit ";
                        $sql.= "WHERE id={$v}";
                        DB::query(1, $sql)->execute();
                        break;
                    case 114:
                        $sql = "UPDATE sline_outdoor_suit_price SET profit=basicprice*{$settlement_val},price=basicprice+profit,childprofit=childbasicprice*{$settlement_val},childprice=childbasicprice+childprofit ";
                        $sql.= "WHERE suitid={$v} AND day>={$date} AND supplier_channel_id={$params['channel_id']}";
                        DB::query(1, $sql)->execute();
                        break;
                    case 118:
                        $sql = "UPDATE sline_techan_suit SET profit=basicprice*{$settlement_val},price=basicprice+profit ";
                        $sql.= "WHERE id={$v}";
                        DB::query(1, $sql)->execute();
                        break;
                    case 121:
                        $sql = "UPDATE sline_food_suit SET profit=basicprice*{$settlement_val},price=basicprice+profit ";
                        $sql.= "WHERE id={$v}";
                        DB::query(1, $sql)->execute();
                        break;
                    default:
                        if($params['type_id']>199){
                            $sql = "UPDATE sline_model_suit_price SET profit=basicprice*{$settlement_val},price=basicprice+profit ";
                            $sql.= "WHERE suitid={$v} AND day>={$date} AND supplier_channel_id={$params['channel_id']}";
                            DB::query(1, $sql)->execute();
                        }
                        break;
                }
            }
        }else{
            /*批量加利润只能针供应价大于0的才能修改，即basicprice成本价字段*/
            foreach ($suit_id as $v){
                switch ($params['type_id'])
                {
                    case 1:
                        /*分别执行不同人群的利润加价*/
                        $sql = "UPDATE sline_line_suit_price SET adultprofit={$settlement_val},adultprice=adultbasicprice+adultprofit ";
                        $sql.= "WHERE adultbasicprice>0 AND day>={$date} AND suitid={$v} AND supplier_channel_id={$params['channel_id']}";
                        DB::query(1, $sql)->execute();
                        $sql = "UPDATE sline_line_suit_price SET childprofit={$settlement_val},childprice=childbasicprice+childprofit ";
                        $sql.= "WHERE childbasicprice>0 AND day>={$date} AND suitid={$v} AND supplier_channel_id={$params['channel_id']}";
                        DB::query(1, $sql)->execute();
                        $sql = "UPDATE sline_line_suit_price SET oldprofit={$settlement_val},oldprice=oldbasicprice+oldprofit ";
                        $sql.= "WHERE oldbasicprice>0 AND day>={$date} AND suitid={$v} AND supplier_channel_id={$params['channel_id']}";
                        DB::query(1, $sql)->execute();
                        $sql = "UPDATE sline_line_suit_price SET people4_profit={$settlement_val},people4_price=people4_basicprice+people4_profit ";
                        $sql.= "WHERE people4_basicprice>0 AND day>={$date} AND suitid={$v} AND supplier_channel_id={$params['channel_id']}";
                        DB::query(1, $sql)->execute();
                        $sql = "UPDATE sline_line_suit_price SET people5_profit={$settlement_val},people5_price=people5_basicprice+people5_profit ";
                        $sql.= "WHERE people5_basicprice>0 AND day>={$date} AND suitid={$v} AND supplier_channel_id={$params['channel_id']}";
                        DB::query(1, $sql)->execute();
                        $sql = "UPDATE sline_line_suit_price SET people6_profit={$settlement_val},people6_price=people6_basicprice+people6_profit ";
                        $sql.= "WHERE people6_basicprice>0 AND day>={$date} AND suitid={$v} AND supplier_channel_id={$params['channel_id']}";
                        DB::query(1, $sql)->execute();
                        break;
                    case 2:
                        $sql = "UPDATE sline_hotel_room_price SET profit={$settlement_val},price=basicprice+profit ";
                        $sql.= "WHERE suitid={$v} AND day>={$date} AND basicprice>0 AND supplier_channel_id={$params['channel_id']}";
                        DB::query(1, $sql)->execute();
                        break;
                    case 3:
                        $sql = "UPDATE sline_car_suit_price SET adultprofit={$settlement_val},adultprice=adultbasicprice+adultprofit ";
                        $sql.= "WHERE suitid={$v} AND day>={$date} AND adultbasicprice>0 AND supplier_channel_id={$params['channel_id']}";
                        DB::query(1, $sql)->execute();
                        break;
                    case 5:
                        $sql = "UPDATE sline_spot_ticket_price SET adultprofit={$settlement_val},adultprice=adultbasicprice+adultprofit ";
                        $sql.= "WHERE ticketid={$v} AND day>={$date} AND adultbasicprice>0 AND supplier_channel_id={$params['channel_id']}";
                        DB::query(1, $sql)->execute();
                        break;
                    case 13:
                        $sql = "UPDATE sline_tuan SET profit={$settlement_val},price=basicprice+profit ";
                        $sql.= "WHERE id={$v} AND basicprice>0";
                        DB::query(1, $sql)->execute();
                        break;
                    case 114:
                        /*分别执行不同人群的利润加价*/
                        $sql = "UPDATE sline_outdoor_suit_price SET profit={$settlement_val},price=basicprice+profit ";
                        $sql.= "WHERE suitid={$v} AND day>={$date} AND basicprice>0 AND supplier_channel_id={$params['channel_id']}";
                        DB::query(1, $sql)->execute();
                        $sql = "UPDATE sline_outdoor_suit_price SET childprofit={$settlement_val},childprice=childbasicprice+childprofit, ";
                        $sql.= "WHERE suitid={$v} AND day>={$date} AND childbasicprice>0 AND supplier_channel_id={$params['channel_id']}";
                        DB::query(1, $sql)->execute();
                        break;
                    case 118:
                        $sql = "UPDATE sline_techan_suit SET profit={$settlement_val},price=basicprice+profit ";
                        $sql.= "WHERE id={$v} AND basicprice>0";
                        DB::query(1, $sql)->execute();
                        break;
                    case 121:
                        $sql = "UPDATE sline_food_suit SET profit={$settlement_val},price=basicprice+profit ";
                        $sql.= "WHERE id={$v} AND basicprice>0";
                        DB::query(1, $sql)->execute();
                        break;
                    default:
                        if($params['type_id']>199){
                            $sql = "UPDATE sline_model_suit_price SET profit={$settlement_val},price=basicprice+profit ";
                            $sql.= "WHERE suitid={$v} AND day>={$date} AND basicprice>0 AND supplier_channel_id={$params['channel_id']}";
                            DB::query(1, $sql)->execute();
                        }
                        break;
                }
            }
        }
    }

    /**
     * 佣金设置列表页
     */
    public function action_batch_set_commission()
    {
        $action = $this->params['action'];
        $type_id = $this->params['type_id'];
        if(empty($action)){
            $channel_list = St_Functions::get_ota_channel(null,true);
            $supplier_list = DB::select()->from('supplier')->where("verifystatus=3")->execute()->as_array();
            $type_id_list = implode(',',array_unique(array_filter(explode(',',implode(',',array_column($supplier_list,'authorization'))))));
            if($type_id_list){
                $type_list = DB::select()->from('model')->where("id IN({$type_id_list})")->execute()->as_array();
                $this->assign('type_list',$type_list);
            }

            $this->assign('channel_list',$channel_list);
            $this->assign('supplier_list',$supplier_list);
            $this->assign('type_id',$type_id);
            $this->display('stourtravel/commission/list');
        }elseif($action=='read'){
            $params = $_GET;
            $params['channel_id'] = $params['channel_id']?$params['channel_id']:1;
            switch ($params['type_id'])
            {
                case 1:
                    $list = $this->line_suit($params);
                    break;
                case 2:
                    $list = $this->hotel_suit($params);
                    break;
                case 3:
                    $list = $this->car_suit($params);
                    break;
                case 5:
                    $list = $this->spot_suit($params);
                    break;
                case 13:
                    $list = $this->tuan_suit($params);
                    break;
                case 114:
                    $list = $this->outdoor_suit($params);
                    break;
                case 118:
                    $list = $this->techan_suit($params);
                    break;
                case 121:
                    $list = $this->food_suit($params);
                    break;
                default:
                    if($params['type_id']>199){
                        $list = $this->tongyong_suit($params);
                    }else{
                        $list = array(
                            'total' => 0,
                            'lists' => array(),
                        );
                    }
                    break;
            }

            echo json_encode($list);
        }
    }

    public function tongyong_suit($params)
    {
        $date = strtotime(date('Ymd',time()));
        $sql = "SELECT a.id,b.id AS product_id,a.suitname,a.settlement_type,b.title FROM sline_model_suit AS a ";
        $sql.= "LEFT JOIN sline_model_archive AS b ON(a.productid=b.id) ";
        $sql.= "LEFT JOIN sline_model_suit_price AS c ON(c.suitid=a.id) ";
        $sql.= "WHERE b.supplierlist!='' AND c.supplier_channel_id={$params['channel_id']} AND c.day>={$date} AND b.typeid={$params['type_id']} AND b.id IS NOT NULL AND a.settlement_type={$params['settlement_id']} ";
        if($params['keyword']){
            $sql.= "AND (a.suitname like '%{$params['keyword']}%' OR b.title LIKE '%{$params['keyword']}%') ";
        }
        if($params['supplier_id']){
            $sql.= "AND b.supplierlist={$params['supplier_id']} ";
        }
        $data = $this->query($sql,$params);

        return $data;
    }

    public function food_suit($params)
    {
        $sql = "SELECT a.id,b.id AS product_id,a.suitname,a.settlement_type,b.title FROM sline_food_suit AS a ";
        $sql.= "LEFT JOIN sline_food AS b ON(a.productid=b.id) ";
        $sql.= "WHERE b.supplierlist!='' AND a.settlement_type={$params['settlement_id']} ";
        if($params['keyword']){
            $sql.= "AND (a.suitname like '%{$params['keyword']}%' OR b.title LIKE '%{$params['keyword']}%') ";
        }
        if($params['supplier_id']){
            $sql.= "AND b.supplierlist={$params['supplier_id']} ";
        }
        $data = $this->query($sql,$params);

        return $data;
    }

    public function techan_suit($params)
    {
        $sql = "SELECT a.id,b.id AS product_id,a.suitname,a.settlement_type,b.title FROM sline_techan_suit AS a ";
        $sql.= "LEFT JOIN sline_techan AS b ON(a.productid=b.id) ";
        $sql.= "WHERE b.supplierlist!='' AND a.settlement_type={$params['settlement_id']} ";
        if($params['keyword']){
            $sql.= "AND (a.suitname like '%{$params['keyword']}%' OR b.title LIKE '%{$params['keyword']}%') ";
        }
        if($params['supplier_id']){
            $sql.= "AND b.supplierlist={$params['supplier_id']} ";
        }
        $data = $this->query($sql,$params);

        return $data;
    }

    public function outdoor_suit($params)
    {
        $date = strtotime(date('Ymd',time()));
        $sql = "SELECT a.id,b.id AS product_id,a.suitname,a.settlement_type,b.title FROM sline_outdoor_suit AS a ";
        $sql.= "LEFT JOIN sline_outdoor AS b ON(a.outdoorid=b.id) ";
        $sql.= "LEFT JOIN sline_outdoor_suit_price AS c ON(a.id=c.suitid) ";
        $sql.= "WHERE b.supplierlist!='' AND c.supplier_channel_id={$params['channel_id']} AND c.day>={$date} AND b.id IS NOT NULL AND a.settlement_type={$params['settlement_id']} ";
        if($params['keyword']){
            $sql.= "AND (a.suitname like '%{$params['keyword']}%' OR b.title LIKE '%{$params['keyword']}%') ";
        }
        if($params['supplier_id']){
            $sql.= "AND b.supplierlist={$params['supplier_id']} ";
        }
        $data = $this->query($sql,$params);

        return $data;
    }

    public function tuan_suit($params)
    {
        $sql = "SELECT id,id as product_id,'--' as suitname,settlement_type,title FROM sline_tuan AS a WHERE supplierlist!='' AND settlement_type={$params['settlement_id']} ";
        if($params['keyword']){
            $sql.= "AND title like '%{$params['keyword']}%' ";
        }
        if($params['supplier_id']){
            $sql.= "AND a.supplierlist={$params['supplier_id']} ";
        }
        $data = $this->query($sql,$params);

        return $data;
    }

    public function spot_suit($params)
    {
        $date = strtotime(date('Ymd',time()));
        $sql = "SELECT a.id,a.spotid as product_id,a.title as suitname,a.settlement_type,b.title FROM sline_spot_ticket AS a ";
        $sql.= "LEFT JOIN sline_spot AS b ON(a.spotid=b.id) ";
        $sql.= "LEFT JOIN sline_spot_ticket_price AS c ON(c.ticketid=a.id) ";
        $sql.= "WHERE a.supplierlist !='' AND c.supplier_channel_id={$params['channel_id']} AND c.day>={$date} AND b.id IS NOT NULL AND a.settlement_type={$params['settlement_id']} ";
        if($params['keyword']){
            $sql.= "AND (a.title like '%{$params['keyword']}%' OR b.title LIKE '%{$params['keyword']}%') ";
        }
        if($params['supplier_id']){
            $sql.= "AND a.supplierlist={$params['supplier_id']} ";
        }
        $data = $this->query($sql,$params);

        return $data;
    }

    public function car_suit($params)
    {
        $date = strtotime(date('Ymd',time()));
        $sql = "SELECT a.id,a.carid as product_id,a.suitname,a.settlement_type,b.title FROM sline_car_suit AS a ";
        $sql.= "LEFT JOIN sline_car AS b ON(a.carid=b.id) ";
        $sql.= "LEFT JOIN sline_car_suit_price AS c ON(c.suitid=a.id) ";
        $sql.= "WHERE b.supplierlist !='' AND c.supplier_channel_id={$params['channel_id']} AND c.day>={$date} AND b.id IS NOT NULL AND a.settlement_type={$params['settlement_id']} ";
        if($params['keyword']){
            $sql.= "AND (a.suitname like '%{$params['keyword']}%' OR b.title LIKE '%{$params['keyword']}%') ";
        }
        if($params['supplier_id']){
            $sql.= "AND b.supplierlist={$params['supplier_id']} ";
        }
        $data = $this->query($sql,$params);

        return $data;
    }

    public function hotel_suit($params)
    {
        $date = strtotime(date('Ymd',time()));
        $sql = "SELECT a.id,a.hotelid as product_id,a.roomname as suitname,a.settlement_type,b.title FROM sline_hotel_room AS a ";
        $sql.= "LEFT JOIN sline_hotel AS b ON(a.hotelid=b.id) ";
        $sql.= "LEFT JOIN sline_hotel_room_price AS c ON(c.suitid=a.id) ";
        $sql.= "WHERE b.supplierlist !='' AND c.supplier_channel_id={$params['channel_id']} AND c.day>={$date} AND a.settlement_type={$params['settlement_id']} AND b.id IS NOT NULL ";
        if($params['keyword']){
            $sql.= "AND (a.roomname like '%{$params['keyword']}%' OR b.title LIKE '%{$params['keyword']}%') ";
        }
        if($params['supplier_id']){
            $sql.= "AND b.supplierlist={$params['supplier_id']} ";
        }
        $data = $this->query($sql,$params);

        return $data;
    }

    public function line_suit($params)
    {
        $date = strtotime(date('Ymd',time()));
        $sql = "SELECT a.id,a.lineid as product_id,a.suitname,a.settlement_type,b.title FROM sline_line_suit AS a ";
        $sql.= "LEFT JOIN sline_line AS b ON(a.lineid=b.id) ";
        $sql.= "LEFT JOIN sline_line_suit_price AS c ON(a.id=c.suitid) ";
        $sql.= "WHERE b.supplierlist !='' AND c.supplier_channel_id={$params['channel_id']} AND c.day>={$date} AND a.settlement_type={$params['settlement_id']} AND b.id IS NOT NULL ";
        if($params['keyword']){
            $sql.= "AND (a.suitname like '%{$params['keyword']}%' OR b.title LIKE '%{$params['keyword']}%') ";
        }
        if($params['supplier_id']){
            $sql.= "AND b.supplierlist={$params['supplier_id']} ";
        }
        $data = $this->query($sql,$params);

        return $data;
    }

    public function query($sql,$params)
    {
        $sql.= "GROUP BY a.id ";
        if($params['type_id']!=13){
            $sql.= "ORDER BY b.addtime DESC ";
        }else{
            $sql.= "ORDER BY addtime DESC ";
        }
        $total = DB::query(1,$sql)->execute()->count();
        $sql.= "LIMIT {$params['start']},{$params['limit']}";
        $list = DB::query(1, $sql)->execute()->as_array();

        foreach ($list as &$v){
            $v['settlement_name'] = $v['settlement_type']==1?'结算价':'销售价';
            if($v['settlement_type']==2){
                $settlement_info = DB::select()->from('supplier_settlement_config')
                    ->where("suit_id={$v['id']} and type_id={$params['type_id']} and channel_id={$params['channel_id']}")
                    ->execute()->current();
                if($settlement_info){
                    $settlement_val = $settlement_info['settlement_key']==1?bcmul($settlement_info['settlement_val'],100):$settlement_info['settlement_val'];
                    $v['commission_mode'] = $settlement_info['settlement_key']==1?'销售价抽取'.$settlement_val.'%':'订单固定返佣'.$settlement_val;
                }else{
                    $v['commission_mode'] = '还未配置任何信息';
                }
            }else{
                $v['commission_mode'] = '结算价加价部分';
            }
        }

        return array(
            'total' => $total,
            'lists' => $list,
            'success' => 'success'
        );
    }
}
